#!/bin/bash
source /home/xinchen/crontab/common.sh
LocalDir=$(cd "$(dirname $0)";pwd) # 当前脚本目录绝对路径
LocalFile="${LocalDir}/$(basename $0)" # 当前脚本文件绝对路径
DATE=$(date +%F)
Date=$(date "+%Y%m%d")
Time=$(date +%H%M)
Hour=$(date +%H)
Week=$(date +%w)
LogDir=/home/it/logs/quants/TradeData
LogFile=$LogDir/zz1000_${DATE}.log
Filepath=/home/it/quants/TradeData/TradePlan.sh

Strategy=stock_alpha_v2

cd $LocalDir
mkdir -p $LogDir

send(){
title=$1
LogFile=$2
if [ $? -ne 0 ] ;then
    status="ERROR" # 可能无权限、可能执行失败
    SendFile=$LogFile
    content="程序执行异常 ${LogFile}"
elif ! grep -qi "error" $LogFile ;then
    status="OK"
    content="${LogFile}"
    SendFile=""
else
    status="ERROR"
    SendFile=$LogFile
    content="${LogFile}"    
fi 

Message="${status}: ${title} 
主机: ${Hostname} [$(date +'%F %T')]
脚本: ${LocalFile}
日志: ${content}"
echo $Message
sendOps
sendDaily
}

case $1 in
"test")
    LogFile=$LogDir/zz1000_test_${DATE}.log
    if [ ${Week} -eq 5 ] ;then
        TestDate=$(date -d 'next monday' +%Y%m%d)
    else
        TestDate=$(date -d next-day +%Y%m%d)
    fi


    echo "运行测试: ${LocalDir}/TradePlan.py --strategy $Strategy --backtest 1 --date $TestDate" &> $LogFile
    ${LocalDir}/TradePlan.py --strategy $Strategy --backtest 1 --date $TestDate &>> $LogFile
	send

;;
*)
    echo "运行生产: ${LocalDir}/TradePlan.py --strategy $Strategy --date $Date" &> $LogFile
#@send "检查zz1000 Plan交易计划" "$LogFile"

    skip_time=093200 #判断和跳出脚本循环时间
    start_time=093105 #脚本运行时间
    end_time=093200 #脚本结束时间
    LogFile="$LogDir/zz1000_t0_${DATE}.log"
    current_second=$(date +%H%M%S)  # 获取当前时间的分钟和秒，比如现在是17:05:02格式为 170502

    # 如果小于9:32 程序等待到最早9:31执行, 9:32就不运行了所以就不是 小于等于
    if [[ $((10#${current_second})) -lt $((10#${skip_time}))  ]]  ;then
        while true ;do
            current_second=$(date +%H%M%S)
            # 脚本在 start_time ~ end_time 范围运行
            if [[ $((10#${current_second})) -ge $((10#${start_time}))  ]] && [[ $((10#${current_second})) -lt $((10#${end_time}))  ]] ;then
                echo "这个脚本只能等到上一个程序,并且等待9:31才能运行,超过9:32就不能运行了. 运行生产: ${LocalDir}/TradePlan.py --strategy stock_alpha_v2-t0 --date $Date" &>> $LogFile
                if [ $? -eq 0 ] ;then
                    echo "OK 跑931的好了!" &>> $LogFile
                else
                    echo "ERROR 931的跑失败了,  ${LocalDir}/TradePlan.py --strategy stock_alpha_v2-t0 --date $Date" &>> $LogFile
                fi
                break
            elif [[ $((10#${current_second})) -ge $((10#${skip_time}))  ]]  ;then
                echo "当前时间${current_second}, 超过 ${skip_time} 退出脚本" &>> $LogFile
                break
            fi
        done
    else
        echo "OK 跑931的跳过, 当前时间${current_second}, 大于${skip_time}!" &>> $LogFile
    fi
   # send "检查zz1000 T0交易计划" "$LogFile"
;;
esac
